package com.tiantian.web.controller.common;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.RandomUtil;
import com.tiantian.common.annotation.Log;
import com.tiantian.common.annotation.RateLimiter;
import com.tiantian.common.constant.CacheConstants;
import com.tiantian.common.constant.Constants;
import com.tiantian.common.core.domain.ResponseResult;
import com.tiantian.common.enums.BusinessType;
import com.tiantian.common.enums.LimitType;
import com.tiantian.common.helper.LoginHelper;
import com.tiantian.common.utils.redis.RedisUtils;
import com.tiantian.framework.config.properties.MailProperties;
import com.tiantian.system.service.EmailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;


@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
public class CaptchaController {

    private final MailProperties mailProperties;
    private final EmailService emailService;


    /**
     * 邮箱验证码
     *
     * @param email 邮箱
     */
    @GetMapping("/captchaEmail")
    @SaIgnore
    @RateLimiter(time = 150, count = 2, limitType = LimitType.IP)
    @Log(title = "获取注册验证码", businessType = BusinessType.CAPTCHA)
    public ResponseResult<Void> emailCode(@NotBlank(message = "邮箱不能为空") String email) {
        if (!mailProperties.getEnabled()) {
            return ResponseResult.fail("当前系统没有开启邮箱功能!");
        }
        String key = CacheConstants.CAPTCHA_CODE_KEY + email;
        String code = RandomUtil.randomNumbers(6);
        RedisUtils.set(key, code, Constants.CAPTCHA_EXPIRATION);
        try {
            // 异步发送邮件
            String subject = "注册验证码";
            String msg = "您的正在进行注册，验证码为：" + code + "，请勿将验证码泄露于他人，本条验证码有效期为" + Constants.CAPTCHA_EXPIRATION / 60 + "分钟，请尽快填写。";
            emailService.sendEmail(email, subject, msg);
        } catch (Exception e) {
            log.error("验证码短信发送异常 => {}", e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.ok();
    }

    @GetMapping("/updateEmail")
    @SaCheckLogin
    @RateLimiter(time = 30, count = 1, limitType = LimitType.IP)
    @Log(title = "获取修改邮箱验证码", businessType = BusinessType.CAPTCHA)
    public ResponseResult<Void> getUpdateEmailCode(@NotBlank(message = "邮箱不能为空") String email) {
        if (!mailProperties.getEnabled()) {
            return ResponseResult.fail("当前系统没有开启邮箱功能!");
        }
        String key = CacheConstants.UPDATE_EMAIL_CAPTCHA_CODE_KEY + email;
        String code = RandomUtil.randomNumbers(6);
        RedisUtils.set(key, code, Constants.CAPTCHA_EXPIRATION);
        try {
            // 异步发送邮件
            String subject = "修改邮箱";
            String msg = "您的正在修改邮箱, 验证码为：" + code + "，请勿将验证码泄露于他人，本条验证码有效期为" + Constants.CAPTCHA_EXPIRATION / 60 + "分钟，请尽快填写。";
            emailService.sendEmail(email, subject, msg);
        } catch (Exception e) {
            log.error("验证码短信发送异常 => {}", e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.ok();
    }

}
